<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="1" data-page-identification="x_hb0xe6o0k2">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
            <div class="top-tab">
                <a-radio-group v-model:value="state.radioValue" button-style="solid" @change="radioChange">
                    <a-radio-button v-for="(item, index) in state.tabList" :value="item.id">{{
                        item.regionName
                    }}</a-radio-button>
                </a-radio-group>
            </div>
            <div class="content">
                <div class="opration">
                    <div class="opration-left">
                        <a-form-item label="时间范围">
                            <a-date-picker
                                style="width: 200px"
                                v-model:value="state.searchWeek"
                                picker="week"
                                :format="weekFormat"
                                @change="handleWeekChange"
                            />
                        </a-form-item>
                        <div class="color-content">
                            <div class="color-tip">
                                <div class="color-item">
                                    <div class="cycle-green"></div>
                                    <div class="color-msg">项目当前无异常</div>
                                </div>
                            </div>
                            <div class="color-tip">
                                <div class="color-item">
                                    <div class="cycle-orange"></div>
                                    <div class="color-msg">低风险、在可控范围内</div>
                                </div>
                            </div>
                            <div class="color-tip">
                                <div class="color-item">
                                    <div class="cycle-red"></div>
                                    <div class="color-msg">中风险、需相关领导关注</div>
                                </div>
                            </div>
                            <div class="color-tip">
                                <div class="color-item">
                                    <div class="cycle-black"></div>
                                    <div class="color-msg">重大风险，需要专题会议，领导决策</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                        <a-button type="primary" @click="exportToPDF">导出</a-button>
                    </div>
                </div>

                <div class="kb-table-box" ref="contentToExport">
                    <a-table
                        bordered
                        :columns="state.columns"
                        :data-source="state.dataSource"
                        :scroll="{ y: 580 }"
                        :loading="state.tableLoading"
                        :pagination="false"
                    >
                        <template #bodyCell="{ column, record, text }">
                            <template
                                v-if="
                                    column.dataIndex === 'healthRangeName' ||
                                    column.dataIndex === 'healthPlanName' ||
                                    column.dataIndex === 'healthTeamName' ||
                                    column.dataIndex === 'healthCrossGroupName' ||
                                    column.dataIndex === 'healthProblemRiskName' ||
                                    column.dataIndex === 'healthRangeName'
                                "
                            >
                                <div class="father-div">
                                    <div class="status-div" :style="getStyle(text)"></div>
                                </div>
                            </template>
                            <template v-if="column.dataIndex === 'healthRemark'">
                                <div>
                                    <div class="align-left" v-for="(line, index) in text.split('\n')" :key="index">
                                        {{ line }}
                                    </div>
                                </div>
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>
            <!-- end vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    import isoWeek from 'dayjs/plugin/isoWeek'

    dayjs.extend(isoWeek)
    onMounted(() => {
        // 获取当前日期
        const today = dayjs()
        // 计算本周的周一和周日
        const startOfWeek = today.startOf('week').add(1, 'day').format('YYYY-MM-DD') // 周一
        const endOfWeek = today.endOf('week').add(1, 'day').format('YYYY-MM-DD') // 周日
        // 输出结果
        const currentWeekRange = [startOfWeek, endOfWeek]
        const s = dayjs(today).startOf('week').format('M月D日')
        const e = dayjs(today).endOf('week').format('M月D日')
        const timeFrame = [`${s}-${e}`]
        state.searchWeek = dayjs(startOfWeek)
        state.timeFrameList = currentWeekRange
        getRegionList()
        getData()
    })
    const state = reactive({
        tabList: [],
        radioValue: '',
        timeFrameList: [],
        searchWeek: '',
        tableLoading: false,
        columns: [
            {
                title: '项目名称',
                align: 'center',
                dataIndex: 'projectName'
            },
            {
                title: '项目阶段',
                align: 'center',
                dataIndex: 'stageName'
            },
            {
                title: '项目健康状态',
                align: 'center',
                resizable: true,
                children: [
                    {
                        title: '范围',
                        dataIndex: 'healthRangeName',
                        align: 'center',
                        width: 160,
                        ellipsis: true,
                        resizable: true
                    },

                    {
                        title: '计划',
                        dataIndex: 'healthPlanName',
                        align: 'center',
                        width: 160,
                        ellipsis: true,
                        resizable: true
                    },
                    {
                        title: '团队',
                        dataIndex: 'healthTeamName',
                        align: 'center',
                        width: 160,
                        ellipsis: true,
                        resizable: true
                    },
                    {
                        title: '跨组协同',
                        dataIndex: 'healthCrossGroupName',
                        align: 'center',
                        width: 160,
                        ellipsis: true,
                        resizable: true
                    },
                    {
                        title: '问题风险',
                        dataIndex: 'healthProblemRiskName',
                        align: 'center',
                        width: 160,
                        ellipsis: true,
                        resizable: true
                    }
                ]
            },
            {
                title: '特别说明',
                align: 'center',
                width: 400,
                dataIndex: 'healthRemark'
            }
        ],
        dataSource: []
    })
    // 日期格式化
    const weekFormat = date => {
        const year = date.year()
        const month = date.month() + 1
        // 获取当月的第一天
        const firstDayOfMonth = dayjs(date).startOf('month')
        // 计算当前日期是本月的第几周
        const weekOfMonth = date.week() - firstDayOfMonth.week() + 1
        return `${year}年${month}月第${weekOfMonth}周`
    }
    // 筛选日期格式化
    const handleWeekChange = date => {
        if (date) {
            const start = dayjs(date).startOf('isoWeek').format('YYYY-MM-DD')
            const end = dayjs(date).endOf('isoWeek').format('YYYY-MM-DD')
            state.timeFrameList = [start, end]
        } else {
            state.timeFrameList = []
        }
        getData()
    }
    const colorMap = {
        '黑色': '#262626',
        '绿色': '#52C41A ',
        '红色': '#FF2A00',
        '黄色': '#FABA32'
    }
    //     获取颜色
    function getStyle(text) {
        return {
            backgroundColor: colorMap[text]
        }
    }
    // 区域
    function getRegionList() {
        get('/solution-ppm/api/v2/built-in-system-ppm/cooperation/config_region/display').then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state.tabList = data.data
            state.radioValue = data.data[0]?.id
        })
    }
    //     切换区域
    function radioChange() {
        getData()
    }
    function getData() {
        state.tableLoading = true
        post('/solution-ppm/api/v2/built-in-system-ppm/week_report/search', {
            dateRangeList: state.timeFrameList,
            pageNo: 1,
            pageSize: 19999,
            searchType: 'ALL',
            configAreaId: state.radioValue,
          viewStatus:true
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                state.dataSource = data.data.dataList
            })
            .finally(() => {
                state.tableLoading = false
            })
    }
    import html2canvas from 'html2canvas'
    import jsPDF from 'jspdf'
    const contentToExport = ref(null)
    // const exportToPDF = async () => {
    //     if (contentToExport.value) {
    //         // 使用 html2canvas 将内容转换为 Canvas
    //         const canvas = await html2canvas(contentToExport.value, { scale: 2 })
    //         const imgData = canvas.toDataURL('image/png')
    //
    //         // 创建 jsPDF 实例
    //         const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' })
    //
    //         const imgWidth = 210 // A4 纸张宽度
    //         const pageHeight = 295 // A4 纸张高度
    //         const imgHeight = (canvas.height * imgWidth) / canvas.width
    //         let heightLeft = imgHeight
    //         let position = 0
    //
    //         // 添加第一页
    //         pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
    //         heightLeft -= pageHeight
    //
    //         // 添加更多页面
    //         while (heightLeft > 0) {
    //             position = heightLeft - imgHeight
    //             pdf.addPage()
    //             pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
    //             heightLeft -= pageHeight
    //         }
    //
    //         // 保存 PDF
    //         pdf.save('document.pdf')
    //     }
    // }
    // TODO:导出方法
    function downloadPdf(response, name) {
        const blob = new Blob([response], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
        })
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = name // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href)
        return href
    }

    function exportToPDF() {
        post(
            `/solution-ppm/api/v2/built-in-system-ppm/cooperation/kanban/project_status_export`,
            {
                dateRangeList: state.timeFrameList,
                pageNo: 1,
                pageSize: 19999,
                searchType: 'ALL',
                configAreaId: state.radioValue
            },
            {
                responseType: 'arraybuffer'
            }
        ).then(res => {
            let name = state.tabList.find(item => item.id == state.radioValue).regionName
            if (name) {
                downloadPdf(res, `${name}.pdf`)
            } else {
                downloadPdf(res, '健康状态.pdf')
            }
        })
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    /*样式*/
    .page_root {
        overflow: hidden;
    }
    .top-tab {
        background: #ffffff;
        border-radius: 2px;
        height: 64px;
        padding: 16px 24px;
        margin-bottom: 18px;
    }
    .content {
        background: #ffffff;
        border-radius: 2px;
        padding: 24px;
        height: calc(100vh - 130px);
    }
    .opration {
        display: flex;
        justify-content: space-between;
    }
    .color-item {
        display: flex;
        align-items: center;
        position: relative;
        top: 5px;
    }
    .cycle-green,
    .cycle-orange,
    .cycle-red,
    .cycle-black {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        margin-right: 8px;
    }
    .color-content {
        display: flex;
        justify-content: space-between;
        margin-left: 16px;
    }
    .cycle-green {
        background-color: #52c41a;
    }
    .cycle-orange {
        background: #faba32;
    }
    .cycle-red {
        background: #ff2a00;
    }
    .cycle-black {
        background: #262626;
    }
    .color-msg {
        font-size: 14px;
        color: #262626;
        font-weight: 400;
    }
    .opration-left {
        display: flex;
    }
    .color-tip {
        margin-left: 24px;
    }
    .kb-table-box:deep(.@{ant-prefix}-table-thead) > tr > th {
        background-color: #ebf1ff;
        color: #262626;
        font-weight: 600;
        padding: 4px 4px;
        border-right: 1px solid #d9d9d9 !important;
    }
    .kb-table-box:deep(
            .ant3-table.ant3-table-bordered
                > .ant3-table-container
                > .ant3-table-content
                > table
                > thead
                > tr:not(:last-child)
                > th
        ) {
        border-bottom: 1px solid #d9d9d9;
    }
    .kb-table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #595959;
        border-bottom: 1px solid #d9d9d9;
        padding: 6px 16px;
        word-break: break-all;
    }
    .kb-table-box:deep(
            .ant3-table.ant3-table-bordered
                > .ant3-table-container
                > .ant3-table-header
                > table
                > thead
                > tr:not(:last-child)
                > th
        ) {
        border-bottom: 1px solid #d9d9d9;
    }
    .status-div {
        height: 28px;
        width: 28px;
        border-radius: 50%;
    }
    .father-div {
        display: flex;
        justify-content: center;
    }
    .align-left {
        text-align: left;
    }
</style>
